<template>
  <div class>
    <PageTitle :title="pageTitle"></PageTitle>
    <div class="form-wrapper">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!--        <el-form-item label="商品名称" prop="goods_id">-->
        <!--          <el-select v-model="ruleForm.goods_id" placeholder="请选择商品">-->
        <!--            <template v-for="(item, index) in tableData">-->
        <!--              <el-option :label="item.goods_name" :value="item.id" :key="index"></el-option>-->
        <!--            </template>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="所属公司" prop="company">-->
        <!--          <el-select v-model="ruleForm.company" placeholder="请选择所属公司">-->
        <!--            <template v-for="(item, index) in companyArr">-->
        <!--              <el-option :label="item.company" :value="item.id" :key="index"></el-option>-->
        <!--            </template>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="商品品牌" prop="fication_id">
          <el-select v-model="ruleForm.fication_id" placeholder="请选择商品品牌">
            <template v-for="(item, index) in ficationArr">
              <el-option :label="item.fication_name" :value="item.oid" :key="index"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图/视频">
          <el-switch
            v-model="coverType"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="视频"
            inactive-text="图片"
          ></el-switch>
        </el-form-item>
        <el-form-item label="封面图" prop="coverFileList" v-if="!coverType">
          <Upload
            :fileListArr="ruleForm.coverFileList"
            :fileListName="'coverFileList'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></Upload>
        </el-form-item>
        <el-form-item label="封面视频" prop="coverFileList" v-else>
          <UploadVideo
            :fileListArr="ruleForm.coverFileList"
            :fileListName="'coverFileList'"
            :fileMaxCount="1"
            @fileChange="fileChange"
          ></UploadVideo>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import PageTitle from "@/components/pageTitle/PageTitle.vue";
import Upload from "@/components/upload/Upload.vue";
import UploadVideo from "@/components/uploadVideo/UploadVideo.vue";
export default {
  name: "GoodsAdd",
  components: {
    PageTitle,
    Upload,
    UploadVideo
  },
  activated() {
    this.$goTop();
    this.getCompany();
    this.getFication();
    this._getList();

    if (this.$route.params.id && this.$route.params.url) {
      this.detailId = this.$route.params.id;
      this.detailUrl = this.$route.params.url;
      this.getDetails();
    }
  },
  deactivated() {
    this.$destroy();
  },
  data() {
    return {
      detailId: "",
      detailUrl: "",

      companyFlag: false,
      coverFlag: "",
      companyArr: [],
      tableData: [],
      pageNum: 1,
      totalCount: 0,
      pageSize: 10,
      status: "0", //  筛选参数
      search: "", //搜索参数
      ficationArr: [],
      ficationList: [],
      coverType: false,
      ruleForm: {
        goods_id: "",
        price: "",
        describe: "",
        stock: "",
        company: "",
        fication_id: "",
        coverFileList: [], //type: 1 为图片    type: 2 为视频
        fileList: []
      },
      rules: {
        goods_id: [
          { required: true, message: "请选择商品", trigger: "change" }
        ],
        company: [
          { required: true, message: "请选择所属公司", trigger: "change" }
        ],
        fication_id: [
          { required: true, message: "请选择商品品牌", trigger: "change" }
        ],
        coverFileList: [
          { type: "array", required: true, message: "请上传封面" }
        ]
      }
    };
  },
  watch: {
    // company(company) {
    //   if(this.companyFlag) {
    //     this.ruleForm.fication_id = ''
    //   }
    //   this.companyFlag = true
    //   this.ficationArr = this.ficationList.filter(item => {
    //     return company == item.company_id
    //   })
    //   console.log(this.ficationArr)
    // },
    //   coverType() {
    //     this.ruleForm.coverFileList = []
    //   }
  },
  computed: {
    pageTitle() {
      return "内容中心";
    },
    submitUrl() {
      return this.$api + "/v1/goods/detail";
    },
    coverFileIdArr() {
      return this.ruleForm.coverFileList
        .map(item => {
          return item.id;
        })
        .toString();
    },
    fileIdArr() {
      return this.ruleForm.fileList
        .map(item => {
          return item.id;
        })
        .toString();
    },

    company() {
      return this.ruleForm.company;
    }
  },
  methods: {
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    quickAdd() {
      let obj = JSON.parse(localStorage.getItem("goodMsg"));
      this.ruleForm.goods_name = obj.goods_name;
      this.ruleForm.price = obj.price;
      this.ruleForm.describe = obj.describe;
      this.ruleForm.stock = obj.stock;
      this.ruleForm.company = obj.company;
      this.ruleForm.fication_id = obj.fication_id;
      obj.fileList.forEach(item => {
        this.ruleForm.fileList.push({
          id: item.response.data.id,
          url: item.response.data.url
        });
      });
    },
    async getDetails() {
      let {
        data: { data }
      } = await this.$axios({
        url: this.$api + "/v1/goods/detailed",
        method: "POST",
        data: {
          id: this.detailId
        }
      });
      this.ruleForm.goods_name = data.goods_name;
      this.ruleForm.price = data.price;
      this.ruleForm.describe = data.describe;
      this.ruleForm.stock = data.stock;
      this.ruleForm.company = data.company;
      this.ruleForm.fication_id = data.fication;
      if (data.url.indexOf(".mp4") !== -1) {
        this.coverType = true;
      }
      if (data.url) {
        this.ruleForm.fileList.push({
          id: data.id,
          url: data.url
        });
        this.ruleForm.coverFileList.push({
          id: data.id,
          url: data.url
        });
      }
    },

    async change1() {
      let data = await this.$axios({
        url: this.$api + "/v1/goods/within",
        method: "POST",
        data: {
          cover_id: this.coverFileIdArr,
          id: this.detailId
        }
      });
      /*  console.log('data', data); */
      if (data.data.code == 0) {
        setTimeout(() => {
          this.$router.go(-1);
        }, 1500);
      }
    },
    async _getList() {
      let {
        data: { data, code }
      } = await this.$axios({
        url: this.$api + "/v1/goods/list",
        method: "GET",
        params: {
          size: this.pageSize,
          current: this.pageNum,
          state: this.status,
          title: this.search
        }
      });
      if (code == 0) {
        this.tableData = data.items;
        this.totalCount = data.page.totalCount;
      }
    },
    fileChange(data) {
      /* console.log(data); */
      this.ruleForm[data.el] = data.arr;
    },
    async getCompany() {
      let {
        data: { data }
      } = await this.$axios({
        url: this.$api + "/v1/company/list",
        method: "GET",
        params: {
          size: 1000,
          current: 1
        }
      });
      this.companyArr = data.items;
    },
    async getFication() {
      let {
        data: { data }
      } = await this.$axios({
        url: this.$api + "/v1/fication/list",
        method: "GET",
        params: {
          size: 1000,
          current: 1
        }
      });
      /*  console.log( data.items) */
      this.ficationArr = data.items;
      // this.ficationArr = this.ficationList.filter(item => {
      //   return company == item.company_id
      // })
      if (this.$route.params.id != "none") {
        // this._get()
      }
    },
    // 提交表单
    submitForm(formName) {
      if (this.detailId && this.detailUrl) {
        this.change1();
      } else {
        this.$refs[formName].validate(valid => {
          if (!valid) {
            return false;
          } else {
            this._submit();
          }
        });
      }
    },
    _submit: _.throttle(
      async function() {
        let {
          data: { code, data }
        } = await this.$axios({
          url: this.submitUrl,
          method: "POST",
          data: {
            // goods_id: this.ruleForm.goods_id,
            fication: this.ruleForm.fication_id,
            cover_id: this.coverFileIdArr
          }
        });
        if (code == 0) {
          this.$message.success(data);
          if (this.$route.params.id == "none") {
            let obj = {
              goods_name: this.ruleForm.goods_name,
              price: this.ruleForm.price,
              describe: this.ruleForm.describe,
              stock: this.ruleForm.stock,
              company: this.ruleForm.company,
              fication_id: this.ruleForm.fication_id,
              fileList: this.ruleForm.fileList
            };
            localStorage.setItem("goodMsg", JSON.stringify(obj));
          }
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        }
      },
      2000,
      { trailing: false }
    )
  }
};
</script>

<style lang='scss'>
.form-wrapper {
  width: 50%;
}
</style>
